//
//  WBComposeViewController.m
//  WeiBoOC
//
//  Created by 韩菲菲 on 16/8/17.
//  Copyright © 2016年 韩菲菲. All rights reserved.
//

#import "WBComposeViewController.h"
#import "WBUserAccountViewModel.h"
#import "WBComposeTextView.h"
#import <Masonry.h>
#import "WBComposeBottomView.h"
#import "WBComposePictureView.h"
#import "UIImage+WBImage.h"
#import "WBNetworkTool.h"
#import <SVProgressHUD.h>
#import "WBEmoticonKeyBoardView.h"

@interface WBComposeViewController ()<UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

//自定义nav titleview
@property (nonatomic , strong) UILabel *customTitleView;

//自定义textView
@property (nonatomic , strong) WBComposeTextView *customTextView;

//自定义底部视图
@property (nonatomic , strong) WBComposeBottomView *bottomView;

//自定义选择图片视图
@property (nonatomic , strong) WBComposePictureView *pictureView;

//自定义Inputview键盘
@property (nonatomic , strong) WBEmoticonKeyBoardView *keyBoardView;

@end

@implementation WBComposeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    [self setNav];
}

- (WBComposeTextView *)customTextView
{
    if(!_customTextView)
    {
        _customTextView = [[WBComposeTextView alloc] init];
        
        //设置上下滚动
        _customTextView.alwaysBounceVertical = YES;
        //设置占位文字
        _customTextView.placeholder = @"微博31期微博31期微博31期微博31期微博31期微博31期微博31期微博31期微博31期微博31期微博31期微博31期";
        
        //设置字体大小
        _customTextView.textFont = [UIFont systemFontOfSize:18];
        
        //设置代理 监听文本变化  按钮是否可以被点击
        _customTextView.delegate = self;
        
    }
    
    return _customTextView;
}


- (UILabel *)customTitleView
{
    if(!_customTitleView)
    {
        _customTitleView = [[UILabel alloc] init];
        NSString *name = [WBUserAccountViewModel sharedWBUserAccountViewModel].userAccount.screen_name;
        NSString *str = [NSString stringWithFormat:@"欢迎回来\n%@",name];
        
        //设置富文本
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
        [attrStr addAttributes:@{NSForegroundColorAttributeName:AppColor,NSFontAttributeName:[UIFont systemFontOfSize:12]} range:[str rangeOfString:name]];
        
        _customTitleView.attributedText = attrStr;
        //设置换行
        _customTitleView.numberOfLines = 0;
        //设置文字居中显示
        _customTitleView.textAlignment = NSTextAlignmentCenter;
        //根据文字适应大小
        [_customTitleView sizeToFit];
        
    }
    
    return _customTitleView;
    
}

- (WBComposeBottomView *)bottomView
{
    if(!_bottomView)
    {
        
        _bottomView = [[WBComposeBottomView alloc] init];
        
    }
    
    return _bottomView;
    
}

- (WBComposePictureView *)pictureView
{
    if(!_pictureView)
    {
        _pictureView = [[WBComposePictureView alloc] init];
        
    }
    return _pictureView;
}

- (WBEmoticonKeyBoardView *)keyBoardView
{
    if(!_keyBoardView)
    {
        _keyBoardView = [[WBEmoticonKeyBoardView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 216)];
        
    }
    
    return _keyBoardView;

}

#pragma mark - 设置UI
- (void)setupUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    //添加自定义text
    [self.view addSubview:self.customTextView];
    [self.view addSubview:self.bottomView];
    [self.customTextView addSubview:self.pictureView];
    
    //设置约束
    [self.customTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(self.view).mas_offset(UIEdgeInsetsZero);
        
    }];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.leading.bottom.trailing.mas_equalTo(self.view);
        make.height.mas_equalTo(44);
        
    }];
    [self.pictureView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.customTextView).mas_offset(100);
        make.size.mas_offset(CGSizeMake(kScreenW - 20, kScreenW - 20));
        make.centerX.mas_equalTo(self.customTextView);
        
    }];
    
    __weak typeof(self) weakSelf = self;
    self.bottomView.block = ^(HMComposeBottomViewType type){
        
        switch (type) {
            case Picture:
            
                [weakSelf selectImage];
                
                break;
            case Mention:
                
                NSLog(@"@被点击");
                
                break;
            case Trend:
                
                NSLog(@"#被点击");
                
                break;
            case Emoticon:
                
                NSLog(@"笑脸被点击");
                //自定义inputview
                [weakSelf switchKeyBoardView];
                
                break;
            case Add:
                NSLog(@"add被点击");
                break;
        }
        
    };
    
    self.pictureView.block = ^(){
        
        [weakSelf selectImage];
        
    };
    
    //键盘弹出的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(KeyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

#pragma mark - 修改键盘frame
- (void)KeyboardWillChangeFrame:(NSNotification *)notification
{
    
    
    NSValue *endFrameValue = notification.userInfo[@"UIKeyboardFrameEndUserInfoKey"];
    
    NSString *time = notification.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"];
    
    double timeDouble = [time doubleValue];
    
    CGRect endFrameRect = endFrameValue.CGRectValue;
    
    
    //更新约束
    [self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.mas_equalTo(self.view).offset(endFrameRect.origin.y - kScreenH);
        
    }];
    
    
    [UIView animateWithDuration:timeDouble animations:^{
        
        [self.view layoutIfNeeded];
    }];
    
}
//移除通知
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)setNav
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(sendAction)];
    
    //按钮不能被点击
    self.navigationItem.rightBarButtonItem.enabled = NO;
    //自定义view
    self.navigationItem.titleView = self.customTitleView;
    
}

#pragma mark - 导航按钮点击事件的实现
- (void)cancelAction
{
    [self.customTextView resignFirstResponder];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 发布按钮点击实现
- (void)sendAction
{
    NSLog(@"发布按钮点击了");
    
    //点击发布微博以后 发送请求 https://api.weibo.com/2/statuses/update.json
    
    self.pictureView.images.count == 0 ? [self update] : [self upload];
    
}

//发布文字微博
- (void)update
{
    
    [SVProgressHUD show];
    
    [[WBNetworkTool sharedWBNetworkTool] updateSinaWithStatus:self.customTextView.text andSuccess:^(id responseObject) {
        
        [self showStatusWithHUD:@"发布成功"];
        
        //发送通知
        [[NSNotificationCenter defaultCenter]postNotificationName:@"sinaSendAccess" object:nil];
        [self cancelAction];
        
        
    } andFailure:^(NSError *error) {
        [self showStatusWithHUD:@"发布失败"];
        
        
    }];
    
}

//发布图片文字微博
- (void)upload
{
    
    [SVProgressHUD show];
    
    [[WBNetworkTool sharedWBNetworkTool] uploadSinaWithStatus:self.customTextView.text andImage:self.pictureView.images.firstObject andSuccess:^(id responseObject) {
        [self showStatusWithHUD:@"发布成功"];
        
        //发送通知
        [[NSNotificationCenter defaultCenter]postNotificationName:@"sinaSendAccess" object:nil];
        [self cancelAction];
        
    } andFailure:^(NSError *error) {
        [self showStatusWithHUD:@"发布失败"];
        
    }];
    
}

- (void)showStatusWithHUD:(NSString *)status
{
    
    [SVProgressHUD showSuccessWithStatus:status];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [SVProgressHUD dismiss];
        
    });
    
}


#pragma mark - textView的代理实现
- (void)textViewDidChange:(UITextView *)textView
{
    self.navigationItem.rightBarButtonItem.enabled = textView.hasText;
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.customTextView resignFirstResponder];
    
}


#pragma mark - 相册选择图片
- (void)selectImage
{
    UIImagePickerController *pickerVc = [[UIImagePickerController alloc] init];
    
    //设置代理
    pickerVc.delegate = self;
    
    //跳转控制器
    [self.navigationController presentViewController:pickerVc animated:YES completion:nil];
    
}

- (void)switchKeyBoardView
{
    if(self.customTextView.inputView == nil)
    {
        self.customTextView.inputView = self.keyBoardView;
        
        self.bottomView.isEmoticon = YES;
    
    }else
    {
        self.customTextView.inputView = nil;
        
        self.bottomView.isEmoticon = NO;
    
    }
    
    //刷新键盘
    [self.customTextView reloadInputViews];
    
    //变为第一响应者
    [self.customTextView becomeFirstResponder];

}

//点击取消按钮的时候会调用
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

//选择图片以后会调用这个
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    //记录图片
    UIImage *image = info[@"UIImagePickerControllerOriginalImage"];
    
    //压缩图片
    [self.pictureView addImage:[UIImage handleImage:image andWidth:600]];
    
    //销毁控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    
}
@end
